<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 存储回调函数
        let activeEffect

        const bucket = new WeakMap();

        const data = { text: "hello world!" }

        const obj = new Proxy(data, {
            get(target, key) {
                track(target, key)
                return target[key]
            },
            set(target, key, newVal) {
                target[key] = newVal

                trigger(target, key)
            }
        })

        function track(target, key) {
            let depsMap = bucket.get(target)
            if (!depsMap) {
                bucket.set(target, (depsMap = new Map()))
            }
            let deps = depsMap.get(key)

            if (!deps) {
                depsMap.set(key, (deps = new Set()))
            }
            deps.add(activeEffect)
        }
        function trigger(target, key) {
            const depsMap = bucket.get(target)
            if (!depsMap) return
            const effects = depsMap.get(key)
            effects && effects.forEach(fn => fn())
        }

        function effect(fn) {
            activeEffect = fn
            fn()
        }

        effect(() => {
            console.log("effect run")
            document.body.innerText = obj.text
        })

        setInterval(() => {
            obj.text = "hello vue3"
        }, 1000)
    </script>
</body>

</html>